home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-02 / comp-pas.zip / TUTORPAS.ZIP / TUTOR9.DOC < prev   
Text File  |  1989-05-21  |  33KB  |  946 lines

  1. OPA A
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  
  8.  
  9.  
  10.  
  11.  
  12.  
  13.  
  14.  
  15.  
  16.  
  17.  
  18.  
  19.  
  20.  
  21.  
  22.  
  23.  
  24.  
  25.  
  26.  
  27.  
  28.                             LET'S BUILD A COMPILER!
  29.  
  30.                                        By
  31.  
  32.                             Jack W. Crenshaw, Ph.D.
  33.  
  34.                                  16 April 1989
  35.  
  36.  
  37.                               Part IX: A TOP VIEW
  38.  
  39.  
  40.  
  41.  
  42.  
  43.  
  44.  
  45.  
  46.  
  47.  
  48.  
  49.  
  50.  
  51.  
  52.  
  53.  
  54.  
  55.  
  56.  
  57.  
  58.  
  59.  
  60.  
  61.  
  62.  
  63.  
  64.  
  65.  
  66.  
  67. PA A
  68.  
  69.  
  70.  
  71.  
  72.  
  73.        *****************************************************************
  74.        *                                                               *
  75.        *                        COPYRIGHT NOTICE                       *
  76.        *                                                               *
  77.        *   Copyright (C) 1989 Jack W. Crenshaw. All rights reserved.   *
  78.        *                                                               *
  79.        *****************************************************************
  80.  
  81.  
  82.        INTRODUCTION
  83.  
  84.        In  the  previous  installments,  we  have  learned  many of  the
  85.        techniques required to  build  a full-blown compiler.  We've done
  86.        both  assignment   statements   (with   Boolean   and  arithmetic
  87.        expressions),  relational operators, and control constructs.   We
  88.        still haven't  addressed procedure or function calls, but even so
  89.        we  could  conceivably construct a  mini-language  without  them.
  90.        I've  always  thought  it would be fun to see just  how  small  a
  91.        language  one  could  build  that  would still be useful.   We're
  92.        ALMOST in a position to do that now.  The  problem  is: though we
  93.        know  how  to  parse and translate the constructs, we still don't
  94.        know quite how to put them all together into a language.
  95.  
  96.        In those earlier installments, the  development  of  our programs
  97.        had  a decidedly bottom-up flavor.  In  the  case  of  expression
  98.        parsing,  for  example,  we  began  with  the  very lowest  level
  99.        constructs, the individual constants  and  variables,  and worked
  100.        our way up to more complex expressions.
  101.  
  102.        Most people regard  the  top-down design approach as being better
  103.        than  the  bottom-up  one.  I do too,  but  the  way  we  did  it
  104.        certainly seemed natural enough for the kinds of  things  we were
  105.        parsing.
  106.  
  107.        You mustn't get  the  idea, though, that the incremental approach
  108.        that  we've  been  using  in  all these tutorials  is  inherently
  109.        bottom-up.  In  this  installment  I'd  like to show you that the
  110.        approach can work just as well when applied from the top down ...
  111.        maybe better.  We'll consider languages such as C and Pascal, and
  112.        see how complete compilers can be built starting from the top.
  113.  
  114.        In the next installment, we'll  apply the same technique to build
  115.        a  complete  translator  for a subset of the KISS language, which
  116.        I'll be  calling  TINY.    But one of my goals for this series is
  117.        that you will  not only be able to see how a compiler for TINY or
  118.        KISS  works,  but  that you will also be able to design and build
  119.        compilers for your own languages.  The C and Pascal examples will
  120.        help.    One  thing I'd like you  to  see  is  that  the  natural
  121.        structure of the compiler depends very much on the language being
  122.        translated, so the simplicity and  ease  of  construction  of the
  123.        compiler  depends  very  much  on  letting the language  set  the
  124.        program structure.ABAB
  125.                                      - 2 -A*A*
  126. PA A
  127.  
  128.  
  129.  
  130.  
  131.  
  132.        It's  a bit much to produce a full C or Pascal compiler here, and
  133.        we won't try.   But we can flesh out the top levels far enough so
  134.        that you can see how it goes.
  135.  
  136.        Let's get started.
  137.  
  138.  
  139.        THE TOP LEVEL
  140.  
  141.        One of the biggest  mistakes  people make in a top-down design is
  142.        failing  to start at the true top.  They think they know what the
  143.        overall structure of the  design  should be, so they go ahead and
  144.        write it down.
  145.  
  146.        Whenever  I  start a new design, I always like to do  it  at  the
  147.        absolute beginning.   In  program design language (PDL), this top
  148.        level looks something like:
  149.  
  150.  
  151.             begin
  152.                solve the problem
  153.             end
  154.  
  155.  
  156.        OK, I grant  you that this doesn't give much of a hint as to what
  157.        the next level is, but I  like  to  write it down anyway, just to
  158.        give me that warm feeling that I am indeed starting at the top.
  159.  
  160.        For our problem, the overall function of a compiler is to compile
  161.        a complete program.  Any definition of the  language,  written in
  162.        BNF,  begins here.  What does the top level BNF look like?  Well,
  163.        that depends quite a bit on the language to be translated.  Let's
  164.        take a look at Pascal.
  165.  
  166.  
  167.        THE STRUCTURE OF PASCAL
  168.  
  169.        Most  texts  for  Pascal  include  a   BNF   or  "railroad-track"
  170.        definition of the language.  Here are the first few lines of one:
  171.  
  172.  
  173.             <program> ::= <program-header> <block> '.'
  174.  
  175.             <program-header> ::= PROGRAM <ident>
  176.  
  177.             <block> ::= <declarations> <statements>
  178.  
  179.  
  180.        We can write recognizers  to  deal  with  each of these elements,
  181.        just as we've done before.  For each one, we'll use  our familiar
  182.        single-character tokens to represent the input, then flesh things
  183.        out a little at a time.    Let's begin with the first recognizer:
  184.        the program itself.A6A6
  185.                                      - 3 -A*A*
  186. PA A
  187.  
  188.  
  189.  
  190.  
  191.  
  192.        To translate this, we'll  start  with a fresh copy of the Cradle.
  193.        Since we're back to single-character  names, we'll just use a 'p'
  194.        to stand for 'PROGRAM.'
  195.  
  196.        To a fresh copy of the cradle, add the following code, and insert
  197.        a call to it from the main program:
  198.  
  199.  
  200.        {--------------------------------------------------------------}
  201.        { Parse and Translate A Program }
  202.  
  203.        procedure Prog;
  204.        var  Name: char;
  205.        begin
  206.           Match('p');            { Handles program header part }
  207.           Name := GetName;
  208.           Prolog(Name);
  209.           Match('.');
  210.           Epilog(Name);
  211.        end;
  212.        {--------------------------------------------------------------}
  213.  
  214.  
  215.        The procedures  Prolog and Epilog perform whatever is required to
  216.        let the program interface with the operating system,  so  that it
  217.        can execute as a program.  Needless to  say,  this  part  will be
  218.        VERY OS-dependent.  Remember, I've been emitting code for a 68000
  219.        running under the OS I use, which is SK*DOS.   I  realize most of
  220.        you are using PC's  and  would rather see something else, but I'm
  221.        in this thing too deep to change now!
  222.  
  223.        Anyhow, SK*DOS is a  particularly  easy OS to interface to.  Here
  224.        is the code for Prolog and Epilog:
  225.  
  226.  
  227.        {--------------------------------------------------------------}
  228.        { Write the Prolog }
  229.  
  230.        procedure Prolog;
  231.        begin
  232.           EmitLn('WARMST EQU $A01E');
  233.        end;
  234.  
  235.  
  236.        {--------------------------------------------------------------}
  237.        { Write the Epilog }
  238.  
  239.        procedure Epilog(Name: char);
  240.        begin
  241.           EmitLn('DC WARMST');
  242.           EmitLn('END ' + Name);
  243.        end;
  244.        {--------------------------------------------------------------}A6A6
  245.                                      - 4 -A*A*
  246. PA A
  247.  
  248.  
  249.  
  250.  
  251.  
  252.        As usual, add  this  code  and  try  out the "compiler."  At this
  253.        point, there is only one legal input:
  254.  
  255.  
  256.             px.   (where x is any single letter, the program name)
  257.  
  258.  
  259.        Well,  as  usual  our first effort is rather unimpressive, but by
  260.        now  I'm sure you know that things  will  get  more  interesting.
  261.        There is one important thing to  note:   THE OUTPUT IS A WORKING,
  262.        COMPLETE, AND EXECUTABLE PROGRAM (at least after it's assembled).
  263.  
  264.        This  is  very  important.  The  nice  feature  of  the  top-down
  265.        approach is that at any stage you can  compile  a  subset  of the
  266.        complete language and get  a  program that will run on the target
  267.        machine.    From here on, then, we  need  only  add  features  by
  268.        fleshing out the language constructs.  It's all  very  similar to
  269.        what we've been doing all along, except that we're approaching it
  270.        from the other end.
  271.  
  272.  
  273.        FLESHING IT OUT
  274.  
  275.        To flesh out  the  compiler,  we  only have to deal with language
  276.        features  one by one.  I like to start with a stub procedure that
  277.        does  nothing, then add detail in  incremental  fashion.    Let's
  278.        begin  by  processing  a block, in accordance with its PDL above.
  279.        We can do this in two stages.  First, add the null procedure:
  280.  
  281.  
  282.        {--------------------------------------------------------------}
  283.        { Parse and Translate a Pascal Block }
  284.  
  285.        procedure DoBlock(Name: char);
  286.        begin
  287.        end;
  288.        {--------------------------------------------------------------}
  289.  
  290.  
  291.        and modify Prog to read:
  292.  
  293.  
  294.        {--------------------------------------------------------------}
  295.        { Parse and Translate A Program }
  296.  
  297.        procedure Prog;
  298.        var  Name: char;
  299.        begin
  300.           Match('p');
  301.           Name := GetName;
  302.           Prolog;
  303.           DoBlock(Name);
  304.           Match('.');
  305.           Epilog(Name);A*A*
  306.                                      - 5 -
  307. PA A
  308.  
  309.  
  310.  
  311.  
  312.  
  313.        end;
  314.        {--------------------------------------------------------------}
  315.  
  316.  
  317.        That certainly  shouldn't change the behavior of the program, and
  318.        it doesn't.  But now the  definition  of Prog is complete, and we
  319.        can proceed to flesh out DoBlock.  That's done right from its BNF
  320.        definition:
  321.  
  322.  
  323.        {--------------------------------------------------------------}
  324.        { Parse and Translate a Pascal Block }
  325.  
  326.        procedure DoBlock(Name: char);
  327.        begin
  328.           Declarations;
  329.           PostLabel(Name);
  330.           Statements;
  331.        end;
  332.        {--------------------------------------------------------------}
  333.  
  334.  
  335.        The  procedure  PostLabel  was  defined  in  the  installment  on
  336.        branches.  Copy it into your cradle.
  337.  
  338.        I probably need to  explain  the  reason  for inserting the label
  339.        where I have.  It has to do with the operation of SK*DOS.  Unlike
  340.        some OS's,  SK*DOS allows the entry point to the main  program to
  341.        be  anywhere in the program.  All you have to do is to give  that
  342.        point a name.  The call  to  PostLabel puts that name just before
  343.        the first executable statement  in  the  main  program.  How does
  344.        SK*DOS know which of the many labels is the entry point, you ask?
  345.        It's the one that matches the END statement  at  the  end  of the
  346.        program.
  347.  
  348.        OK,  now  we  need  stubs  for  the  procedures Declarations  and
  349.        Statements.  Make them null procedures as we did before.
  350.  
  351.        Does the program  still run the same?  Then we can move on to the
  352.        next stage.
  353.  
  354.  
  355.        DECLARATIONS
  356.  
  357.        The BNF for Pascal declarations is:
  358.  
  359.  
  360.             <declarations> ::= ( <label list>    |
  361.                                  <constant list> |
  362.                                  <type list>     |
  363.                                  <variable list> |
  364.                                  <procedure>     |
  365.                                  <function>         )*A6A6
  366.                                      - 6 -A*A*
  367. PA A
  368.  
  369.  
  370.  
  371.  
  372.  
  373.        (Note  that  I'm  using the more liberal definition used by Turbo
  374.        Pascal.  In the standard Pascal definition, each  of  these parts
  375.        must be in a specific order relative to the rest.)
  376.  
  377.        As  usual,  let's  let a single character represent each of these
  378.        declaration types.  The new form of Declarations is:
  379.  
  380.  
  381.        {--------------------------------------------------------------}
  382.        { Parse and Translate the Declaration Part }
  383.  
  384.        procedure Declarations;
  385.        begin
  386.           while Look in ['l', 'c', 't', 'v', 'p', 'f'] do
  387.              case Look of
  388.               'l': Labels;
  389.               'c': Constants;
  390.               't': Types;
  391.               'v': Variables;
  392.               'p': DoProcedure;
  393.               'f': DoFunction;
  394.              end;
  395.        end;
  396.        {--------------------------------------------------------------}
  397.  
  398.  
  399.        Of course, we need stub  procedures for each of these declaration
  400.        types.  This time,  they  can't  quite  be null procedures, since
  401.        otherwise we'll end up with an infinite While loop.  At  the very
  402.        least, each recognizer must  eat  the  character that invokes it.
  403.        Insert the following procedures:
  404.  
  405.  
  406.        {--------------------------------------------------------------}
  407.        { Process Label Statement }
  408.  
  409.        procedure Labels;
  410.        begin
  411.           Match('l');
  412.        end;
  413.  
  414.  
  415.        {--------------------------------------------------------------}
  416.        { Process Const Statement }
  417.  
  418.        procedure Constants;
  419.        begin
  420.           Match('c');
  421.        end;
  422.  
  423.  
  424.        {--------------------------------------------------------------}
  425.        { Process Type Statement }A6A6
  426.                                      - 7 -A*A*
  427. PA A
  428.  
  429.  
  430.  
  431.  
  432.  
  433.        procedure Types;
  434.        begin
  435.           Match('t');
  436.        end;
  437.  
  438.  
  439.        {--------------------------------------------------------------}
  440.        { Process Var Statement }
  441.  
  442.        procedure Variables;
  443.        begin
  444.           Match('v');
  445.        end;
  446.  
  447.  
  448.        {--------------------------------------------------------------}
  449.        { Process Procedure Definition }
  450.  
  451.        procedure DoProcedure;
  452.        begin
  453.           Match('p');
  454.        end;
  455.  
  456.  
  457.        {--------------------------------------------------------------}
  458.        { Process Function Definition }
  459.  
  460.        procedure DoFunction;
  461.        begin
  462.           Match('f');
  463.        end;
  464.        {--------------------------------------------------------------}
  465.  
  466.  
  467.        Now try out the  compiler  with a few representative inputs.  You
  468.        can  mix  the  declarations any way you like, as long as the last
  469.        character  in  the  program is'.' to  indicate  the  end  of  the
  470.        program.  Of course,  none  of  the declarations actually declare
  471.        anything, so you don't need  (and can't use) any characters other
  472.        than those standing for the keywords.
  473.  
  474.        We can flesh out the statement  part  in  a similar way.  The BNF
  475.        for it is:
  476.  
  477.  
  478.             <statements> ::= <compound statement>
  479.  
  480.             <compound statement> ::= BEGIN <statement>
  481.                                           (';' <statement>) END
  482.  
  483.  
  484.        Note that statements can  begin  with  any identifier except END.
  485.        So the first stub form of procedure Statements is:A6A6
  486.                                      - 8 -A*A*
  487. PA A
  488.  
  489.  
  490.  
  491.  
  492.  
  493.        {--------------------------------------------------------------}
  494.        { Parse and Translate the Statement Part }
  495.  
  496.        procedure Statements;
  497.        begin
  498.           Match('b');
  499.           while Look <> 'e' do
  500.              GetChar;
  501.           Match('e');
  502.        end;
  503.        {--------------------------------------------------------------}
  504.  
  505.  
  506.        At  this  point  the  compiler   will   accept   any   number  of
  507.        declarations, followed by the  BEGIN  block  of the main program.
  508.        This  block  itself  can contain any characters at all (except an
  509.        END), but it must be present.
  510.  
  511.        The simplest form of input is now
  512.  
  513.             'pxbe.'
  514.  
  515.        Try  it.    Also  try  some  combinations  of  this.   Make  some
  516.        deliberate errors and see what happens.
  517.  
  518.        At this point you should be beginning to see the drill.  We begin
  519.        with a stub translator to process a program, then  we  flesh  out
  520.        each procedure in turn,  based  upon its BNF definition.  Just as
  521.        the lower-level BNF definitions add detail and elaborate upon the
  522.        higher-level ones, the lower-level  recognizers  will  parse more
  523.        detail  of  the  input  program.    When  the  last stub has been
  524.        expanded,  the  compiler  will  be  complete.    That's  top-down
  525.        design/implementation in its purest form.
  526.  
  527.        You might note that even though we've been adding procedures, the
  528.        output of the program hasn't changed.  That's as  it  should  be.
  529.        At these  top  levels  there  is  no  emitted code required.  The
  530.        recognizers are  functioning as just that: recognizers.  They are
  531.        accepting input sentences, catching bad ones, and channeling good
  532.        input to the right places, so  they  are  doing their job.  If we
  533.        were to pursue this a bit longer, code would start to appear.
  534.  
  535.        The  next  step  in our expansion should  probably  be  procedure
  536.        Statements.  The Pascal definition is:
  537.  
  538.  
  539.            <statement> ::= <simple statement> | <structured statement>
  540.  
  541.            <simple statement> ::= <assignment> | <procedure call> | null
  542.  
  543.            <structured statement> ::= <compound statement> |
  544.                                       <if statement>       |
  545.                                       <case statement>     |
  546.                                       <while statement>    |A*A*
  547.                                      - 9 -
  548. PA A
  549.  
  550.  
  551.  
  552.  
  553.  
  554.                                       <repeat statement>   |
  555.                                       <for statement>      |
  556.                                       <with statement>
  557.  
  558.  
  559.        These  are  starting  to look familiar.  As a matter of fact, you
  560.        have already gone  through  the process of parsing and generating
  561.        code for both assignment statements and control structures.  This
  562.        is where the top level meets our bottom-up  approach  of previous
  563.        sessions.  The constructs will be a little  different  from those
  564.        we've  been  using  for KISS, but the differences are nothing you
  565.        can't handle.
  566.  
  567.        I  think  you can get the picture now as to the  procedure.    We
  568.        begin with a complete BNF  description of the language.  Starting
  569.        at  the  top  level, we code  up  the  recognizer  for  that  BNF
  570.        statement, using stubs  for  the next-level recognizers.  Then we
  571.        flesh those lower-level statements out one by one.
  572.  
  573.        As it happens, the definition of Pascal is  very  compatible with
  574.        the  use of BNF, and BNF descriptions  of  the  language  abound.
  575.        Armed  with  such   a   description,  you  will  find  it  fairly
  576.        straightforward to continue the process we've begun.
  577.  
  578.        You  might  have  a go at fleshing a few of these constructs out,
  579.        just  to get a feel for it.  I don't expect you  to  be  able  to
  580.        complete a Pascal compiler  here  ...  there  are too many things
  581.        such  as  procedures  and types that we haven't addressed yet ...
  582.        but  it  might  be helpful to try some of the more familiar ones.
  583.        It will do  you  good  to  see executable programs coming out the
  584.        other end.
  585.  
  586.        If I'm going to address those issues that we haven't covered yet,
  587.        I'd rather  do  it  in  the context of KISS.  We're not trying to
  588.        build a complete Pascal  compiler  just yet, so I'm going to stop
  589.        the expansion of Pascal here.    Let's  take  a  look  at  a very
  590.        different language.
  591.  
  592.  
  593.        THE STRUCTURE OF C
  594.  
  595.        The C language is quite another matter, as you'll see.   Texts on
  596.        C  rarely  include  a BNF definition of  the  language.  Probably
  597.        that's because the language is quite hard to write BNF for.
  598.  
  599.        One reason I'm showing you these structures now is so that  I can
  600.        impress upon you these two facts:
  601.  
  602.         (1) The definition of  the  language drives the structure of the
  603.             compiler.  What works for one language may be a disaster for
  604.             another.    It's  a very bad idea to try to  force  a  given
  605.             structure upon the compiler.  Rather, you should let the BNF
  606.             drive the structure, as we have done here.A6A6
  607.                                     - 10 -A*A*
  608. PA A
  609.  
  610.  
  611.  
  612.  
  613.  
  614.         (2) A language that is hard to write BNF for  will  probably  be
  615.             hard  to  write  a compiler for, as well.  C  is  a  popular
  616.             language,  and  it  has  a  reputation  for  letting you  do
  617.             virtually  anything that is possible to  do.    Despite  the
  618.             success of Small C, C is _NOT_ an easy language to parse.
  619.  
  620.  
  621.        A C program has  less  structure than its Pascal counterpart.  At
  622.        the top level, everything in C is a static declaration, either of
  623.        data or of a function.  We can capture this thought like this:
  624.  
  625.  
  626.             <program> ::= ( <global declaration> )*
  627.  
  628.             <global declaration> ::= <data declaration>  |
  629.                                      <function>
  630.  
  631.        In Small C, functions  can  only have the default type int, which
  632.        is not declared.  This makes  the  input easy to parse: the first
  633.        token is either "int," "char," or the name  of  a  function.   In
  634.        Small  C, the preprocessor commands are  also  processed  by  the
  635.        compiler proper, so the syntax becomes:
  636.  
  637.  
  638.             <global declaration> ::= '#' <preprocessor command>  |
  639.                                      'int' <data list>           |
  640.                                      'char' <data list>          |
  641.                                      <ident> <function body>     |
  642.  
  643.  
  644.        Although we're really more interested in full C  here,  I'll show
  645.        you the  code corresponding to this top-level structure for Small
  646.        C.
  647.  
  648.  
  649.        {--------------------------------------------------------------}
  650.        { Parse and Translate A Program }
  651.  
  652.        procedure Prog;
  653.        begin
  654.           while Look <> ^Z do begin
  655.              case Look of
  656.               '#': PreProc;
  657.               'i': IntDecl;
  658.               'c': CharDecl;
  659.              else DoFunction(Int);
  660.              end;
  661.           end;
  662.        end;
  663.        {--------------------------------------------------------------}
  664.  
  665.        Note that I've had to use a ^Z to indicate the end of the source.
  666.        C has no keyword such as END or the '.' to otherwise indicate the
  667.        end.A*A*
  668.                                     - 11 -
  669. PA A
  670.  
  671.  
  672.  
  673.  
  674.  
  675.        With full C,  things  aren't  even  this easy.  The problem comes
  676.        about because in full C, functions can also have types.   So when
  677.        the compiler sees a  keyword  like  "int,"  it still doesn't know
  678.        whether to expect a  data  declaration  or a function definition.
  679.        Things get more  complicated  since  the  next token may not be a
  680.        name  ... it may start with an '*' or '(', or combinations of the
  681.        two.
  682.  
  683.        More specifically, the BNF for full C begins with:
  684.  
  685.  
  686.             <program> ::= ( <top-level decl> )*
  687.  
  688.             <top-level decl> ::= <function def> | <data decl>
  689.  
  690.             <data decl> ::= [<class>] <type> <decl-list>
  691.  
  692.             <function def> ::= [<class>] [<type>] <function decl>
  693.  
  694.  
  695.        You  can  now  see the problem:   The  first  two  parts  of  the
  696.        declarations for data and functions can be the same.   Because of
  697.        the  ambiguity  in  the grammar as  written  above,  it's  not  a
  698.        suitable  grammar  for  a  recursive-descent  parser.     Can  we
  699.        transform it into one that is suitable?  Yes, with a little work.
  700.        Suppose we write it this way:
  701.  
  702.  
  703.             <top-level decl> ::= [<class>] <decl>
  704.  
  705.             <decl> ::= <type> <typed decl> | <function decl>
  706.  
  707.             <typed decl> ::= <data list> | <function decl>
  708.  
  709.  
  710.        We  can  build  a  parsing  routine  for  the   class   and  type
  711.        definitions, and have them store away their findings  and  go on,
  712.        without their ever having to "know" whether a function or  a data
  713.        declaration is being processed.
  714.  
  715.        To begin, key in the following version of the main program:
  716.  
  717.  
  718.        {--------------------------------------------------------------}
  719.        { Main Program }
  720.  
  721.        begin
  722.           Init;
  723.           while Look <> ^Z do begin
  724.              GetClass;
  725.              GetType;
  726.              TopDecl;
  727.           end;
  728.        end.A*A*
  729.                                     - 12 -
  730. PA A
  731.  
  732.  
  733.  
  734.  
  735.  
  736.        {--------------------------------------------------------------}
  737.  
  738.  
  739.        For the first round, just make the three procedures stubs that do
  740.        nothing _BUT_ call GetChar.
  741.  
  742.        Does this program work?  Well, it would be hard put NOT to, since
  743.        we're not really asking it to do anything.  It's been said that a
  744.        C compiler will accept virtually any input without choking.  It's
  745.        certainly true of THIS  compiler,  since in effect all it does is
  746.        to eat input characters until it finds a ^Z.
  747.  
  748.        Next, let's make  GetClass  do something worthwhile.  Declare the
  749.        global variable
  750.  
  751.  
  752.             var Class: char;
  753.  
  754.  
  755.        and change GetClass to do the following:
  756.  
  757.  
  758.        {--------------------------------------------------------------}
  759.        {  Get a Storage Class Specifier }
  760.  
  761.        Procedure GetClass;
  762.        begin
  763.           if Look in ['a', 'x', 's'] then begin
  764.              Class := Look;
  765.              GetChar;
  766.              end
  767.           else Class := 'a';
  768.        end;
  769.        {--------------------------------------------------------------}
  770.  
  771.  
  772.        Here, I've used three  single  characters  to represent the three
  773.        storage classes "auto," "extern,"  and  "static."   These are not
  774.        the only three possible classes ... there are also "register" and
  775.        "typedef," but this should  give  you the picture.  Note that the
  776.        default class is "auto."
  777.  
  778.        We  can  do  a  similar  thing  for  types.   Enter the following
  779.        procedure next:
  780.  
  781.  
  782.        {--------------------------------------------------------------}
  783.        {  Get a Type Specifier }
  784.  
  785.        procedure GetType;
  786.        begin
  787.           Typ := ' ';
  788.           if Look = 'u' then begin
  789.              Sign := 'u';A*A*
  790.                                     - 13 -
  791. PA A
  792.  
  793.  
  794.  
  795.  
  796.  
  797.              Typ := 'i';
  798.              GetChar;
  799.              end
  800.           else Sign := 's';
  801.           if Look in ['i', 'l', 'c'] then begin
  802.              Typ := Look;
  803.              GetChar;
  804.           end;
  805.        end;
  806.        {--------------------------------------------------------------}
  807.  
  808.        Note that you must add two more global variables, Sign and Typ.
  809.  
  810.        With these two procedures in place, the compiler will process the
  811.        class and type definitions and store away their findings.  We can
  812.        now process the rest of the declaration.
  813.  
  814.        We  are by no means out of the woods yet, because there are still
  815.        many complexities just in the definition of the  type,  before we
  816.        even get to the actual data or function names.  Let's pretend for
  817.        the moment that we have passed all those gates, and that the next
  818.        thing in the  input stream is a name.  If the name is followed by
  819.        a left paren, we have a function declaration.  If not, we have at
  820.        least one data item,  and  possibly a list, each element of which
  821.        can have an initializer.
  822.  
  823.        Insert the following version of TopDecl:
  824.  
  825.  
  826.        {--------------------------------------------------------------}
  827.        { Process a Top-Level Declaration }
  828.  
  829.        procedure TopDecl;
  830.        var Name: char;
  831.        begin
  832.           Name := Getname;
  833.           if Look = '(' then
  834.              DoFunc(Name)
  835.           else
  836.              DoData(Name);
  837.        end;
  838.        {--------------------------------------------------------------}
  839.  
  840.  
  841.        (Note that, since we have already read the name, we must  pass it
  842.        along to the appropriate routine.)
  843.  
  844.        Finally, add the two procedures DoFunc and DoData:
  845.  
  846.  
  847.        {--------------------------------------------------------------}
  848.        { Process a Function Definition }
  849.  
  850.        procedure DoFunc(n: char);A*A*
  851.                                     - 14 -
  852. PA A
  853.  
  854.  
  855.  
  856.  
  857.  
  858.        begin
  859.           Match('(');
  860.           Match(')');
  861.           Match('{');
  862.           Match('}');
  863.           if Typ = ' ' then Typ := 'i';
  864.           Writeln(Class, Sign, Typ, ' function ', n);
  865.        end;
  866.  
  867.        {--------------------------------------------------------------}
  868.        { Process a Data Declaration }
  869.  
  870.        procedure DoData(n: char);
  871.        begin
  872.           if Typ = ' ' then Expected('Type declaration');
  873.           Writeln(Class, Sign, Typ, ' data ', n);
  874.           while Look = ',' do begin
  875.              Match(',');
  876.              n := GetName;
  877.              WriteLn(Class, Sign, Typ, ' data ', n);
  878.           end;
  879.           Match(';');
  880.        end;
  881.        {--------------------------------------------------------------}
  882.  
  883.  
  884.        Since  we're  still  a long way from producing executable code, I
  885.        decided to just have these two routines tell us what they found.
  886.  
  887.        OK, give this program a try.    For data declarations, it's OK to
  888.        give a list separated by commas.  We  can't  process initializers
  889.        as yet.  We also can't process argument lists for  the functions,
  890.        but the "(){}" characters should be there.
  891.  
  892.        We're still a _VERY_ long way from having a C compiler,  but what
  893.        we have is starting to process the right kinds of inputs,  and is
  894.        recognizing both good  and  bad  inputs.    In  the  process, the
  895.        natural structure of the compiler is starting to take form.
  896.  
  897.        Can we continue this until we have something that acts  more like
  898.        a compiler. Of course we can.  Should we?  That's another matter.
  899.        I don't know about you, but I'm beginning to get dizzy, and we've
  900.        still  got  a  long  way  to  go  to  even  get  past   the  data
  901.        declarations.
  902.  
  903.        At  this  point,  I think you can see how the  structure  of  the
  904.        compiler evolves from the language  definition.    The structures
  905.        we've seen for our  two  examples, Pascal and C, are as different
  906.        as night and day.  Pascal was designed at least partly to be easy
  907.        to parse, and that's  reflected  in the compiler.  In general, in
  908.        Pascal there is more structure and we have a better idea  of what
  909.        kinds of constructs to expect at any point.  In  C,  on the other
  910.        hand,  the  program  is  essentially  a  list   of  declarations,
  911.        terminated only by the end of file.A*A*
  912.                                     - 15 -
  913. PA A
  914.  
  915.  
  916.  
  917.  
  918.  
  919.        We  could  pursue  both  of  these structures much  farther,  but
  920.        remember that our purpose here is  not  to  build a Pascal or a C
  921.        compiler, but rather to study compilers in general.  For those of
  922.        you  who DO want to deal with Pascal or C, I hope I've given  you
  923.        enough of a start so that you can  take  it  from  here (although
  924.        you'll soon need some of the stuff we still haven't  covered yet,
  925.        such as typing and procedure calls).    For the rest of you, stay
  926.        with me through the next installment.  There, I'll be leading you
  927.        through the development of a complete compiler for TINY, a subset
  928.        of KISS.
  929.  
  930.        See you then.
  931.  
  932.  
  933.        *****************************************************************
  934.        *                                                               *
  935.        *                        COPYRIGHT NOTICE                       *
  936.        *                                                               *
  937.        *   Copyright (C) 1989 Jack W. Crenshaw. All rights reserved.   *
  938.        *                                                               *
  939.        *****************************************************************AIAI
  940.  
  941.  
  942.  
  943.  
  944.  
  945.                                     - 16 -A*A*
  946. @